package com.etung.iot.demo.alarm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etung.iot.demo.dao.AlarmMapper;
import com.etung.iot.demo.dao.BoxMapper;
import com.etung.iot.demo.modles.AlarmEntity;
import com.etung.iot.demo.modles.BoxEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class AlarmCacheUtil {
    @Autowired
    private AlarmMapper alarmMapper;
    @Autowired
    private BoxMapper boxMapper;

    private static Map<String, AlarmEntity> alarmEntityMap = new ConcurrentHashMap<>();
    private static Map<String ,BoxEntity> boxEntityMap = new ConcurrentHashMap<> ();

    public AlarmEntity getAlarmEntity(Integer alarmId,String imei){
        String key = imei + "_"+alarmId;
        AlarmEntity alarmEntity = null;
        if (!alarmEntityMap.containsKey(key)){
            alarmEntity = alarmMapper.selectOne(new QueryWrapper<AlarmEntity>()
                    .eq("alarm_id", alarmId)
                    .eq("imei", imei)
            );
        }else {
            alarmEntity = alarmEntityMap.get(key);
        }
        return alarmEntity;
    }

    public BoxEntity getBoxEntity(String imei){
        String key = "box_" + imei;
        BoxEntity boxEntity = null;
        if (!boxEntityMap.containsKey(key)){
            boxEntity = boxMapper.selectOne(new QueryWrapper<BoxEntity>()
                    .eq("imei",imei));
        }else {
            boxEntity = boxEntityMap.get(key);
        }
        return boxEntity;
    }

    public void removeAlarmEntity(String imei){
        alarmEntityMap.entrySet().removeIf(entry -> entry.getKey().startsWith(imei));
    }
    public void removeBoxEntity(String imei){
        String key = "box_" + imei;
        boxEntityMap.entrySet().removeIf(entry->entry.getKey().equals(key));
    }

    public void removeAlarmCache(String imei){
        removeAlarmEntity(imei);
        removeBoxEntity(imei);
    }
}
